<template>
  <div class="flow-setting-right">
    <el-tabs v-model="baseSetActiveTab" class="el-tabs-wrap">
      <el-tab-pane :label="$t('portal.setting.title1')" name="base"> </el-tab-pane>
      <el-tab-pane :label="$t('event.setting.constant.setting_step.name2')" name="senior"></el-tab-pane>
    </el-tabs>
    <div :class="['setting-specific', isCommon && !isEdit ? 'form-design-setting-disabled' : '']" v-show="baseSetActiveTab == 'base'">
      <!--start 表单设置 -->
      <div class="flow-node-setting">
        <h2 class="mt-12">{{ $t('task.setting.taskTypeSetting.flow.components.taskFormSetting') }}</h2>
        <el-button type="text" @click="openFormDesign"> {{$t('task.setting.taskTypeSetting.flow.components.taskNewNodeSetting')}}</el-button>
      </div>
      <!--end 表单设置 -->
      <div class="flow-node-setting flow-node-input">
        <h2 class="mt-12 node-required">{{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeName')}}</h2>
        <el-input class="flow-node-input-content" type="text" :placeholder="$t('common.base.tip.defaultPlaceholder')" v-model="currentNode.title" maxlength="20" show-word-limit></el-input>
      </div>
      <div class="flow-node-setting flow-node-input">
        <h2 class="mt-12 node-required">{{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeButtonName')}}</h2>
        <p class="flow-node-msg">{{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeButtonMsg')}}</p>
        <el-input class="flow-node-input-content" type="text" :placeholder="$t('common.base.tip.defaultPlaceholder')" v-model="flowSetting.nodeBtnName" maxlength="20" show-word-limit></el-input>
      </div>
      <div class="flow-node-setting flow-node-input">
        <h2 class="mt-12 node-required"> {{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeStateName')}}</h2>
         <p class="flow-node-msg"> {{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeStateMsg')}}</p>
        <el-input class="flow-node-input-content" type="text" :placeholder="$t('common.base.tip.defaultPlaceholder')" v-model="flowSetting.nodeStateName" maxlength="20" show-word-limit></el-input>
      </div>
      <div class="flow-node-setting">
        <h2 class="mt-12 node-required">{{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeUser')}}</h2>
        <p class="flow-node-msg">{{$t('task.setting.taskTypeSetting.flow.tabs.taskNodeUserMsg')}}</p>
          <!-- 选人组件 -->
          <el-select
            class="task-user-target-select"
            ref="userComponetSelect"
            :placeholder="$t('common.base.pleaseSelect')"
            @click.native="showSelectUserHandle"
            @remove-tag="removeTagHandle"
            v-model="flowSetting.nodeResponsiblePerson"
            is-search-user
            value-key="name"
            multiple
          >
            <el-option
              v-for="(item, index) in flowSetting.nodeResponsiblePerson"
              :key="`${item.id}_${index}`"
              :label="item.name"
              :origin="item"
              :value="item">
              <template v-if="isOpenData && item.staffId">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </template>
            </el-option>
          </el-select>
      </div>
      <div class="flow-node-setting">
        <h2 class="mt-12">{{ $t('task.setting.flowExtend.message.tip1') }}</h2>
        <div class="flow-node-notify">
          <p class="flow-node-msg">{{ $t('task.setting.flowExtend.message.tip2') }}</p>
          <p @click="beforeSetMsgRemind" class="flow-node-remind">{{ $t('task.setting.flowExtend.message.tip3') }}</p>
        </div>
      </div>
      <!--start 审批设置 -->
      <div class="flow-node-setting setting-specific-approve">
        <h2 class="mt-12">
          {{ $t('task.setting.taskTypeSetting.flow.components.title1') }}
        </h2>
        <approve-setting
          v-if="baseSetActiveTab === 'base'"
          :key="currentNodeId"
          :flowType="currentNodeId"
          :currentNodeId="currentNodeId"
          :options="options.flow"
          :isUpdate="isUpdate"
          :optionMaps="optionMaps"
          :task-type-id="taskTypeId"
          :approve-setting="flowSetting.approveSetting"
          :isCustomNode="true"
          :isCommonNode="isCommon"
          :isNewNormalNode="isNewNormalNode"
          @change="setting => changeApproveSetting(setting, 'assign')"
        />
      </div>
      <!--end 审批设置 -->

      <!--start 超时提醒 -->
      <div class="flow-node-setting setting-specific-overtime mar-b-24">
        <h2 class="title">
          {{ $t('task.setting.taskTypeSetting.flow.components.title6') }}
          <el-switch class="ml-12" v-model="flowSetting.overTimeStatus"/>
        </h2>
        <div class="lh-38" v-show="flowSetting.overTimeStatus">
          {{ preFlowName }}
          <i18n path="task.setting.taskTypeSetting.flow.components.title7">
            <el-input
              place="num"
              class="w-87"
              onkeyup="if(isNaN(value))execCommand('undo')"
              maxlength="4"
              v-model="flowSetting.overTime"
            />
          </i18n>
        </div>
        <div class="lh-38" v-show="flowSetting.overTimeStatus">
          {{ $t('task.setting.taskTypeSetting.flow.components.title8') }}
          <el-select v-model="flowSetting.remindType">
            <el-option v-for="item in overTimeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>

          <template>
            <el-input v-if="flowSetting.remindType === null && !isOpenData" class="w-187" :placeholder="$t('task.setting.taskTypeSetting.flow.components.placeholder1')" readonly :value="getApproverNames(flowSetting.reminders)" @click.native="selectApproveUser" />

            <div class="ui-input-block" @click="selectApproveUser" v-if="flowSetting.remindType === null && isOpenData">
                <span class="placeholder-text" v-if="flowSetting.reminders.length <= 0">
                  {{ $t('task.setting.taskTypeSetting.flow.components.placeholder1') }}
                </span>
              <div>
                <template v-for="(item, index) in flowSetting.reminders">
                  <open-data :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                  <ui-separator :index="index" :list="flowSetting.reminders" :key="`${item.staffId}${uuid()}`" />
                </template>
              </div>
            </div>
          </template>

          <i18n path="task.setting.taskTypeSetting.flow.components.title9">
            <el-select place="num" class="w-87" v-model="flowSetting.isAhead">
              <el-option :label="$t('common.base.before')" :value="1"> </el-option>
              <el-option :label="$t('common.base.after')" :value="0"> </el-option>
            </el-select>
          </i18n>
          <i18n path="task.setting.taskTypeSetting.flow.components.title10">
            <el-input place="num" class="w-87" onkeyup="this.value=this.value.replace(/\D/g,'')" v-model="flowSetting.minutes"/>
          </i18n>
        </div>
      </div>
      <!--end 超时提醒 -->
    </div>

    <div :class="['setting-specific', isCommon && !isEdit ? 'form-design-setting-disabled' : '']" v-show="baseSetActiveTab == 'senior'">
      <div>
        <!--start 触发器 -->
        <trigger-list-setting 
          v-if="false"
          style="margin-top: 12px"
          :subTitle="$t('common.connector.trigger.subTitle', { curFlowName })" 
          bizType="TASK"
          :bizTypeId="taskTypeId" 
          :bizActionCode="type"> 
        </trigger-list-setting>
        <!--end 触发器 -->
        <!-- S 附加组件 -->
        <card-list-setting
          class="flow-node-setting"
          style="margin-top:12px;"
          :subTitle="$t('common.connector.trigger.subTitle', {curFlowName})"
          bizType="TASK"
          :bizTypeId="taskTypeId"
          :bizActionCode="this.type"
          :taskTypeName="taskTypeName"
          :flowCardList="flowCardList"
          :currentNodeId="currentNodeId"
          :isNewNormalNode="isNewNormalNode"
          @flowCardChange="(e) => $emit('flowCardChange', e)"
        >
        </card-list-setting>
        <!-- E 附加组件 -->
      </div>

      <paas-config-contact 
        ref="paasConfigContact"
        :title="$t('common.form.setting.flowNodeSetting.message')"
        :showDynamicMenus="showDynamicMenus"
        :paasContactChooseUsers="flowSetting.nodeResponsiblePerson"
        :showNewNodeFlowLeader="showNewNodeFlowLeader"
        @handleChooseUserSubmit="handleChooseUserSubmit">
      </paas-config-contact>
    </div>
  </div>
</template>
<script>
/** component*/
import ApproveSetting from '@src/modules/setting/task/taskTypeSetting/flow/components/ApproveSetting.vue';
import TriggerListSetting from '@src/modules/connector/components/trigger-list-setting/index.vue';
import PaasConfigContact from '@src/component/compomentV2/PaasConfigContact/index.vue';
import CardListSetting from '@src/modules/setting/task/taskTypeSetting/flow/components/CardListSetting/CardListSetting.vue';
/** model */
import { FlowEnum } from '@model/enum/FlowEnum';
import i18n from '@src/locales';
import { isOpenData, openAccurateTab } from "@src/util/platform";
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import {BaseSelectUserModeEnum} from "@src/component/common/BaseSelectUser";

export default {
  name: 'process-node-setting',
  components: {
    [ApproveSetting.name]: ApproveSetting,
    [TriggerListSetting.name]: TriggerListSetting,
    [PaasConfigContact.name]: PaasConfigContact,
    [CardListSetting.name]: CardListSetting,
  },
  props: {
    overTimeOptions: {
      type: Array,
      default: () => [],
    },
    curFlowName: {
      type: String,
      default: 'create',
    },
    flag: {
      type: Boolean,
      default: false,
    },
    triggerGray: {
      type: Boolean,
      default: false,
    },
    showApproveSetting: {
      type: Boolean,
      default: false,
    },
    taskTypeId: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: 'create',
    },
    flowSetting: {
      type: Object,
      default: () => ({}),
    },
    isUpdate: {
      type: Boolean,
      default: false,
    },
    taskOverTimeModel: {
      type: Object,
      default: () => ({}),
    },
    preFlowName: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    optionMaps: {
      type: Object,
      default: () => ({}),
    },
    currentNode: {
      type: Object,
      default: () => ({}),
    },
    isNewNormalNode: {
      type: Boolean,
      default: false,
    },
    taskTypeName: {
      type: String,
      default: '',
    },
    flowCardList: {
      type: Array,
      default: () => ([]),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    flowProcessList: {
      type: Array,
      default: () => ([]),
    },
  },
  data(){
    return {
      isOpenData,
      baseSetActiveTab:'base',
      showDynamicMenus: [
        i18n.t('common.label.nodeLeader'), 
        i18n.t('common.paas.model.flowManagerTypeEnum.level1')
      ],
    }
  },
  computed: {
    isCommon() {
      return this.currentNode?.isCommon == 1
    },
    showNewNodeFlowLeader() {
      const sysUser = [
        {
          label: i18n.t('task.setting.taskDefaultDispatchSetting.label2'),
          id: 'CREATOR_USER',
        },
        {
          label: i18n.t('task.setting.taskDefaultDispatchSetting.label3'),
          id: 'ALLOT_USER',
        },
        {
          label: i18n.t('task.taskTypes.allot.taskExecutor'),
          id: 'EXECUTOR_USER',
        },
        {
          label: i18n.t('task.taskTypes.allot.taskSynergies'),
          id: 'SYNERGIES_USER',
        }
      ]
      const index = this.flowProcessList.findIndex(item => item.id === this.currentNode?.id);
      let normalUser = [];

      if (index > -1) {
        normalUser = this.flowProcessList.slice(0, index)
          .filter(item => item.type === FlowEnum.NORMAL)
          .map(item => ({
            label: i18n.t('task.setting.taskTypeSetting.flowNewNode.personCharge', { data: item.title }),
            id: item.id,
          }));
      }
      return [ ...sysUser, ...normalUser ]
    },
    // 当前节点的id()
    currentNodeId() {
      return this.currentNode?.id ?? ''
    },
  },
  methods: {
    /** 格式化审批人员名称 */
    getApproverNames(approvers) {
      return approvers?.map((item) => item.displayName)?.join(',');
    },

    /**选择节点负责人 */
    showSelectUserHandle() {
      this.$refs.userComponetSelect?.blur()
      this.$refs.paasConfigContact.visible = true
    },
    /** 删除节点负责人 */
    removeTagHandle() {
      console.log('删除节点负责人')
    },
    /** 选择节点负责人 */
    handleChooseUserSubmit(value) {
      this.$emit('handleChooseUserSubmit', value);
      this.flowSetting.nodeResponsiblePerson = value;
    },
    /** 打开表单设计器 */
    openFormDesign() {
      this.$emit('openFormDesign');
    },
    /** 审批设置  */
    changeApproveSetting(setting, type) {
      this.$emit('changeApproveSetting', setting, type);
    },
    /** 选择指定审批人员 */
    async selectApproveUser() {
      try {
        let selectedUsers = this.flowSetting.reminders;

        let options = {
          title: this.$t('task.setting.taskTypeSetting.flow.components.tip3'),
          max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
          selectedUsers, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
          mode: BaseSelectUserModeEnum.Filter
        };

        const { status, data} = await this.$fast.select.multi.user(options)

        if (status != 0) return;

        this.flowSetting.reminders = data?.users ?? [];
      } catch (e) {
        console.error(e)
      }
    },
    async beforeSetMsgRemind(){
      try {
        // 判断当前节点是否还没有保存
        if(this.isNewNormalNode) {
          await this.$confirm(this.$t('event.setting.serviceEventTypeSetting.flow.tips2'), '', {
            confirmButtonText: this.$t('common.base.save'),
            cancelButtonText: this.$t('common.base.notSaveForNow'),
            type: 'warning',
            closeOnClickModal: false
          })
          this.$eventBus.$emit('task_custom_node_save', true, this.setMsgRemind);
        }else {
          this.setMsgRemind();
        }
      } catch (e) {
        console.error(e)
      }
    },
    // 跳转到消息提醒页面
    setMsgRemind() {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSettingMessage,
        params: 'defaultModule=task',
        fromId,
      })
    },
  },
};
</script>

<style lang="scss">
.el-tabs-wrap {
  height: 40px;
  background: #fff;
  .el-tabs__nav {
    display: flex;
    width: 100%;
    .el-tabs__item {
      width: 50%;
      display: flex;
      justify-content: center;
    }
  }
}
.flow-node-setting {
  position: relative;
  .node-required::before {
    content: "*";
    color: $color-danger;
    position: absolute;
    left: -6px;
    font-size: 12px;
    top: 2px;
  }
  .flow-node-notify {
    display: flex;
    justify-content: space-between;
  }
  .flow-node-msg {
    font-size: 12px;
    color: #8C8C8C;
    line-height: 20px !important;
  }
  .flow-node-remind {
    font-size: 14px;
    color: $color-primary;
    line-height: 22px !important;
    cursor: pointer;
  }
  .flow-node-input-content {
    min-width: 350px;
  }
  .user-target-select {
    width: 100%;
  }
}
.flow-node-input {
  .el-input {
    .el-input__count-inner {
      margin-right: 4px;
    }
  }
}
.task-user-target-select {
    width: 100%;
    margin-top: 8px;

    .el-tag__close {
      display: none !important;
    }
  }
</style>
<style lang="scss">
.setting-specific-overtime {
  .title {
    margin-top: 0 !important;
  }
}
</style>
